package com.woniu.security;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.woniu.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Component
public class JwtUtil {
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expireTime}")
    private int expireTime;

    public String createToken(User user) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.SECOND, expireTime);

        Map<String, Object> payload = new HashMap<>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("id", user.getUserId());
        payload.put("account", user.getAccount());
        payload.put("roleId", user.getRole().getRoleId());

        return JWTUtil.createToken(payload, secret.getBytes());
    }

    //    校验JWT的方法
    public boolean verifyJWT(String token) {
        boolean verify;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            JWT key = jwt.setKey(secret.getBytes());
            verify = key.verify();
        } catch (Exception e) {
            e.printStackTrace();
            verify = false;
        }
        return verify;
    }


    //    获取JWT中用户自定义的数据
    public Object getInfo(String token, String name) {
        JWT jwt = JWTUtil.parseToken(token);
        return jwt.getPayload(name);
    }
}
